import React, { useState, useEffect, useRef } from 'react';
import { Modal, Input, Card, message, Button, Space, Upload, Spin, InputNumber } from 'antd';
import { DeleteOutlined, PictureOutlined, PlaySquareOutlined } from '@ant-design/icons';
import {
  getMessageList,
  saveMsg,
  deleteMsg,
  updateArbitrateStatus,
  sellerWin,
  buyerWin,
  navigationList,
  getTImeCountDown,

} from '@/api/order';
import moment from 'moment';
import { observable } from 'mobx';
import AppStore from '@/store';
import './index.scss';

const store = observable({
  chatList: AppStore.chatList
});

const { Search } = Input;

export default function ChatRoom(props) {
  const {
    visible = true,
    chatRoomInfo = {},
    onClose = () => { },
  } = props

  const $imsocket = window.$imsocket;
  const imgUrl = props.store.imgUrl;

  // 左侧
  const tradeRef = useRef();
  const [leftLoading, setLeftLoading] = useState(false);
  const [tradeData, setTradeData] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const [searchForm, setSearchForm] = useState({
    orderNo: '',
    currentPage: 1,
    pageSize: 10
  })

  const getTradeData = (hasMore, form) => {
    if (!hasMore || leftLoading) {
      return;
    }
    setLeftLoading(true)
    navigationList({
      ...form
    }).then(res => {
      if (res.code === 0) {
        const { records = [], hasNext = true } = res?.data || {};
        setHasMore(hasNext);
        setTradeData((data) => Array.isArray(records) ? [...data, ...records] : []);
      } else {
        setTradeData([])
      }
      setLeftLoading(false)
    }).catch(err => {
      setTradeData([]);
      console.log(err);
      setLeftLoading(false)
    })
  }
  const onSearch = (v) => {
    setHasMore(true);
    const _form = { ...searchForm, orderNo: v, currentPage: 1 };
    setTradeData([]);
    setSearchForm(_form);
    getTradeData(true, _form);
  }
  const searchScroll = () => {
    if (tradeRef.current) {
      const { scrollHeight, clientHeight, scrollTop } = tradeRef.current;
      if (scrollHeight - clientHeight <= scrollTop + 1) {
        if (hasMore) {
          const _form = { ...searchForm, currentPage: searchForm.currentPage + 1 };
          setSearchForm(_form);
          getTradeData(hasMore, _form);
        }
      }
    }
  }
  const changeTradeInfo = (item) => {
    setBaseTradeInfo(item);
    // 加入聊天室
    $imsocket?.joinRoom(item.orderNo).then(async res => {
      if (res.code === 0) {
        console.log('加入成功');
      } else {
        message.error('加入聊天室失败');
      }
    }).catch(err => {
      console.log(err);
    });
  }

  // 中间
  const [baseTradeInfo, setBaseTradeInfo] = useState({});
  const [chatText, setChatText] = useState('');
  const [chatContent, setChatContent] = useState([]);
  const messagesEndRef = useRef();
  // 发送
  const sendChat = () => {
    if (!baseTradeInfo.orderNo) {
      message.error('请选择订单');
      return;
    }
    // sendChatContent({
    //   orderNo: baseTradeInfo.orderNo,
    //   content: chatText,
    // }).then(res => {
    //   if (res.code === 0) {
    //     setChatText('');
    //     setChatContent([...chatContent, res.data]);
    //   } {
    //     message.error('发送失败');
    //   }
    // }).catch(err => {
    //   message.error('发送失败');
    //   console.log(err);
    // })

    // 临时
    setChatContent((chat) => ([...chat, chatText]))
    setChatText('')
  }
  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && e.ctrlKey) {
      setChatText(chatText + '\n');
    } else if (e.key === 'Enter') {
      e.preventDefault();
      sendChat();
    }
  };
  // 上传图片
  const beforeUploadImage = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('请上传图片！');
    };
    return isImage || Upload.LIST_IGNORE;
  }
  const customRequestImage = (info) => {
    // 自定义上传逻辑
    console.log(info.file);
  }
  // 上传视频
  const beforeUploadVideo = (file) => {
    const isVideo = file.type.startsWith('video/');
    if (!isVideo) {
      message.error('请上传视频！');
    };
    return isVideo || Upload.LIST_IGNORE;
  }
  const customRequestVideo = (info) => {
    // 自定义上传逻辑
    console.log(info.file);
  }
  // 仲裁
  const [arbitrationType, setArbitrationType] = useState(1); // 1 转交封控， 2 卖家胜， 3 买家胜
  const [arbitrationVisible, setArbitrationVisible] = useState(false);
  const [arbitrationForm, setArbitrationForm] = useState({
    arbitrateMsg: '',
  })
  const openArbitration = (type) => {
    setArbitrationType(type);
    setArbitrationVisible(true);
  }
  const handleArbitrationOk = () => {
    (arbitrationType === 1 ? updateArbitrateStatus :
      arbitrationType === 2 ? sellerWin : buyerWin
    )({
      transOrderNo: baseTradeInfo.orderNo,
      arbitrateMsg: arbitrationForm.arbitrateMsg,
    }).then(res => {
      if (res.code === 0) {
        setArbitrationVisible(false);
        // 其他操作
      } {
        message.error('提交失败');
      }
    }).catch(err => {
      message.error('提交失败');
    })
  }
  const handleArbitrationCancel = () => {
    setArbitrationVisible(false);
    setArbitrationForm({
      arbitrateMsg: '',
    })
  }


  // 右侧
  const [comTypes, setComTypes] = useState(1); // 1: 欢迎语, 2: 常用语
  const [comPhrases, setComPhrases] = useState([]); // 欢迎语
  const [comTerms, setComTerms] = useState([]); // 常用语
  const [comVisible, setComVisible] = useState(false);
  const [comForm, setComForm] = useState({
    sort: 0,
    content: '',
  });
  const changeComForm = (key, value) => {
    setComForm({ ...comForm, [key]: value })
  };
  // 获取常用数据
  const getCommonData = () => {
    getMessageList({}).then(res => {
      if (res.code === 0) {
        const { commonPhrasesList, commonTermsList } = res.data
        setComPhrases(Array.isArray(commonPhrasesList) ? commonPhrasesList : [])
        setComTerms(Array.isArray(commonTermsList) ? commonTermsList : [])
      } else {
        setComPhrases([]);
        setComTerms([]);
      }
    }).catch(err => {
      setComPhrases([]);
      setComTerms([]);
      console.log(err);
    })
  }
  // 删除常用
  const deleteCommon = (item, type) => {
    deleteMsg({
      id: item.id
    }).then(res => {
      if (res.code === 0) {
        message.success('删除成功');
        getCommonData();
      } else {
        message.error('删除失败');
      }
    }).catch(err => {
      console.log(err);
      message.error('删除失败');
    })
  }
  // 添加常用
  const addCommon = (type) => {
    setComVisible(true);
    setComTypes(type);
  }
  // 取消
  const handleCancel = () => {
    setComVisible(false);
    setComForm({
      sort: 0,
      content: '',
    });
  };
  // 确认提交
  const handleOk = () => {
    saveMsg({
      ...comForm,
      type: comTypes
    }).then(res => {
      if (res.code === 0) {
        message.success('添加成功');
        getCommonData();
        handleCancel();
      } else {
        message.error('添加失败');
      }
    }).catch(err => {
      console.log(err);
      message.error('添加失败');
    })
  };
  // 选择常用语
  const selectCommon = async(item) => {
    if (!baseTradeInfo.orderNo) {
      message.error('请选择订单');
      return;
    }
    let text  = item.content
    if (item.content.includes('{time}')) {
      const res = await getTImeCountDown();
      if (res.code === 0) {
        text = text.replace(/\{time\}/g, res?.data || '--');
        setChatText(text);
      } else {
        message.error('获取时间失败');
      }
    } else {
      text = text.replace(/\{payName\}/g, baseTradeInfo.buyerPayName);
      setChatText(text);
    }
  }
  // 常用语demo
  const commonDemo = (data, type) => {
    return (
      <>
        {
          data && data.length > 0 &&
          data.sort((a, b) => a.sort - b.sort).map((item, index) => {
            return (
              <div
                key={index}
                className="common-item"
                onClick={() => selectCommon(item)}
              >
                <span className="item-content">{item.content}</span>
                <i
                  className="delete-icon"
                  title="删除"
                  onClick={(e) => {
                    e.stopPropagation()
                    deleteCommon(item, type)
                  }}
                >
                  <DeleteOutlined />
                </i>
              </div>
            )
          })
        }
      </>
    )
  }

  useEffect(() => {
    // 监听没生效
    if (!visible) return;
    console.log('触发监听')
    const _chatList = store.chatList?.map(i => ({
      ...i,
      content: JSON.parse(i.content)
    })) || []
    console.log(_chatList, '_chatList')
    setChatContent(() => _chatList)
  }, [store])

  useEffect(() => {
    if (!visible) return;
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
  }, [chatContent])

  useEffect(() => {
    if (visible && chatRoomInfo && JSON.stringify(chatRoomInfo) !== '{}') {
      getTradeData(true, searchForm);
      getCommonData();
    } else {
      setTradeData([]);
      setBaseTradeInfo({});
      setChatText('');
      setChatContent([]);
      setComPhrases([]);
      setComTerms([]);
    }
  }, [visible])

  return (
    <>
      <Modal
        wrapClassName="chat-room-modal-wrapper"
        className="chat-room-modal"
        title="仲裁聊天室"
        width="80%"
        height="90%"
        visible={visible}
        centered={true}
        destroyOnClose={true}
        footer={false}
        onCancel={onClose}
      >
        <div className="chat-room-main">
          <div className="chat-room-left">
            <Card className="chat-room-card">
              <div className="search-group">
                <Search
                  placeholder="请输入搜索关键字"
                  loading={leftLoading}
                  onSearch={onSearch}
                />
              </div>
              <div
                className="result-group"
                ref={tradeRef}
                onScroll={searchScroll}
              >
                {
                  leftLoading && !hasMore && 
                  <div className="loading-box">
                    <Spin />
                  </div> ||
                  <>
                    {tradeData && tradeData.length > 0 &&
                      tradeData.map((item, index) => {
                        return (
                          <div
                            key={index}
                            className="result-item"
                            onClick={() => changeTradeInfo(item)}
                          >
                            <Card className="result-item-card" hoverable>
                              <div className="result-item-info">
                                <label>交易单号：</label>
                                <span title={item.orderNo}>{item.orderNo}</span>
                              </div>
                              <div className="result-item-info">
                                <label>卖家账号：</label>
                                <span title={item.sellerAccount}>{item.sellerAccount}</span>
                              </div>
                              <div className="result-item-info">
                                <label>买家账号：</label>
                                <span title={item.buyerAccount}>{item.buyerAccount}</span>
                              </div>
                              <div className="result-item-info">
                                <label>交易数量：</label>
                                <span title={item.buyerAmount}>{item.buyerAmount}</span>
                              </div>
                            </Card>
                          </div>
                        )
                      })}
                  </>
                }
                <div className="no-more">
                  {!hasMore && '---- 没有更多了 ----'}
                </div>
              </div>
            </Card>
          </div>
          <div className="chat-room-center">
            <Card className="chat-room-card">
              <div className="base-info-group">
                <div className="base-info-item">
                  <label>交易单号：</label>
                  <span title={baseTradeInfo.orderNo}>{baseTradeInfo.orderNo}</span>
                </div>
                <div className="base-info-item">
                  <label>交易数量：</label>
                  <span title={baseTradeInfo.buyerAmount}>{baseTradeInfo.buyerAmount}</span>
                </div>
                <div className="base-info-item">
                  <label>卖家账号：</label>
                  <span title={baseTradeInfo.sellerAccount}>{baseTradeInfo.sellerAccount}</span>
                </div>
                <div className="base-info-item">
                  <label>卖家昵称：</label>
                  <span title={baseTradeInfo.sellerNickName}>{baseTradeInfo.sellerNickName}</span>
                </div>
                <div className="base-info-item">
                  <label>买家账号：</label>
                  <span title={baseTradeInfo.buyerAccount}>{baseTradeInfo.buyerAccount}</span>
                </div>
                <div className="base-info-item">
                  <label>买家昵称：</label>
                  <span title={baseTradeInfo.buyerNickName}>{baseTradeInfo.buyerNickName}</span>
                </div>
              </div>
              <div className="chat-content-box">
                <div className="chat-content-main">
                  <div className="chat-content-list">
                    {chatContent && chatContent.length > 0 &&
                      chatContent.map((item, index) => {
                        return (
                          <div
                            key={index}
                            // userName判断 客服 暂时写死
                            className={`chat-content-item ${item.userName === '客服' ? 'right' : 'left'}`}>
                            <div className="avatar-box">
                              <img src={imgUrl + item.avatarPath || ''} />
                            </div>
                            <div className="msg-box">
                              <div className="msg-date">
                                <span>{ item.nickName }</span>
                                <span>{ moment(item.time).format('YYYY-MM-DD HH:mm:ss') }</span>
                              </div>
                              <div className="msg-content">
                                {item.content.buyRealName}
                              </div>
                            </div>
                          </div>
                        )
                      })
                    }
                    <div ref={messagesEndRef} />
                  </div>
                </div>
                <div className="chat-content-active">
                  <Space>
                    <Button type="primary" disabled={!baseTradeInfo.orderNo} onClick={() => openArbitration(1)}>转交风控</Button>
                    <Button type="primary" disabled={!baseTradeInfo.orderNo} onClick={() => openArbitration(2)}>卖家胜出</Button>
                    <Button type="primary" disabled={!baseTradeInfo.orderNo} onClick={() => openArbitration(3)}>买家胜出</Button>
                  </Space>
                </div>
              </div>
              <div className="chat-input-box">
                <div className="chat-input-main">
                  <Input.TextArea
                    placeholder="请输入聊天内容"
                    value={chatText}
                    onChange={(e) => setChatText(e.target.value)}
                    onKeyDown={handleKeyDown}
                  />
                </div>
                <div className="chat-input-footer">
                  <div className="active-left">
                    <Space>
                      <Upload
                        accept="image/*"
                        action={''}
                        maxCount={1}
                        showUploadList={false}
                        beforeUpload={beforeUploadImage}
                        customRequest={customRequestImage}
                      >
                        <Button icon={<PictureOutlined />} />
                      </Upload>
                      <Upload
                        accept="video/*"
                        action={''}
                        maxCount={1}
                        showUploadList={false}
                        beforeUpload={beforeUploadVideo}
                        customRequest={customRequestVideo}
                      >
                        <Button icon={<PlaySquareOutlined />} />
                      </Upload>
                    </Space>
                  </div>
                  <div className="active-right">
                    <Button type="primary" onClick={sendChat}>发送</Button>
                  </div>
                </div>
              </div>
            </Card>
          </div>
          <div className="chat-room-right">
            <Card className="chat-room-card">
              <div className="common-group">
                <div className="common-phrases">
                  <div className="common-title">常用语展示：</div>
                  <div className="common-group">
                    {commonDemo(comPhrases, 1)}
                  </div>
                </div>
                <div className="common-terms">
                  <div className="common-title">常用术语展示：</div>
                  <div className="common-group">
                    {commonDemo(comTerms, 2)}
                  </div>
                </div>
              </div>

              <div className="active-group">
                <Button block onClick={() => addCommon(1)}>新增常用欢迎语</Button>
                <div className="interval"></div>
                <Button block onClick={() => addCommon(2)}>新增常用术语</Button>
              </div>
            </Card>
          </div>
        </div>
      </Modal>
      <Modal
        wrapClassName="common-option-modal-wrapper"
        className="common-option-modal"
        title="常用语设置"
        visible={comVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <div className="common-option-main">
          <div className="form-item">
            <label>内容：</label>
            <div className="form-content">
              <Input.TextArea
                placeholder="请输入内容"
                value={comForm.content}
                onChange={(e) => changeComForm('content', e.target.value)}
              />
            </div>
          </div>
          <div className="form-item">
            <label>排序：</label>
            <div className="form-content">
              <InputNumber
                placeholder="请输入内容排序"
                value={comForm.sort}
                min={0}
                onChange={(v) => changeComForm('sort', v)}
              />
            </div>
          </div>
        </div>
      </Modal>
      <Modal
        wrapClassName="arbitration-modal-wrapper"
        className="arbitration-modal"
        title={arbitrationType === 1 ? '转交封控' : '订单审核'}
        visible={arbitrationVisible}
        onOk={handleArbitrationOk}
        onCancel={handleArbitrationCancel}
      >
        <div className="arbitration-main">
          <div className="form-item">
            <label>请填写仲裁意见：</label>
            <div className="form-content">
              <Input.TextArea
                row={4}
                placeholder="请填写仲裁意见"
                value={arbitrationForm.arbitrateMsg}
                onChange={(e) => setArbitrationForm({...arbitrationForm, arbitrateMsg: e.target.value})}
              />
            </div>
          </div>
        </div>
      </Modal>
    </>
  )
}
